package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        log.info("拦截到请求：{}", requestURI);
        //如果拦截到的login或者是静态资源请求就放行，否则要验证是否有登录
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/common/upload",
                "/common/download",
                "/backend/**",
                "/front/**",
                "/user/getCode",
                "/user/login"

        };

        boolean check = check(urls, requestURI);
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        // 从session中获取存储的id信息，如果有，则放行，否则返回未登录的消息
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if (employeeId != null) {
            // 获取id，并保存到ThreadLocal中
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request, response);
            return;
        }

        // 从session中获取存储的id信息，如果有，则放行，否则返回未登录的消息
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            // 获取id，并保存到ThreadLocal中
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        // 走到这里说明没有登录，所以要给前端返回未登录的消息
        log.info("用户未登录");
        R<String> msg = R.error("NOTLOGIN");

        // 要把返回对象写成json格式
        String jsonMsg = JSON.toJSONString(msg);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(jsonMsg);

//        filterChain.doFilter(request, response);

    }

    /**
     * 路径校验
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
